<template>
  <div class="app-container">
    <el-form v-show="showSearch" :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="名称" prop="couponName">
        <el-input
          v-model.trim="queryParams.couponName"
          placeholder="请输入名称"
          @keyup.enter="handleSearch(true)"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model.trim="queryParams.remark"
          placeholder="请输入备注"
          @keyup.enter="handleSearch(true)"
        />
      </el-form-item>
      <el-form-item label="用券时间区间" prop="time">
        <el-date-picker
          v-model="queryParams.time"
          type="daterange"
          format="YYYY-MM-DD HH:mm"
          value-format="x"
          date-format="YYYY-MM-DD"
          time-format="HH:mm"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable>
          <el-option label="全部状态" value=""></el-option>
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="城市标签" prop="cityName">
        <el-select
          v-model="queryParams.cityName"
          @change="handleSearch(true)"
          fit-input-width
          placeholder="请选择"
        >
          <el-option
            v-for="item in cityNameOptions"
            :key="item"
            :label="item"
            :value="item"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="&nbsp;">
        <el-button @click="handleSearch(false)">重置</el-button>
        <el-button type="primary" @click="handleSearch(true)">查询</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          v-hasPermi="['marketing:physicalGoods:add']"
          icon="Plus"
          @click="handleAdd()"
          >新增</el-button
        >
      </el-col>
      <right-toolbar v-model="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tableList">
      <el-table-column label="名称" align="center" prop="couponName" show-overflow-tooltip />
      <el-table-column label="城市标签" align="center" prop="cityName" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="{ row }">
          <el-link
            :underline="false"
            :type="statusOptions.find((i) => i.value === row?.status)?.type"
            >{{ statusOptions.find((i) => i.value === row?.status)?.label }}</el-link
          >
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template #default="{ row }"> {{ row?.createTime }} </template>
      </el-table-column>
      <el-table-column label="用券时间" align="center" width="300">
        <template #default="{ row }">
          {{ row.validStartTime ? row.validStartTime + '~\n' + row.validEndTime : '' }}
        </template>
      </el-table-column>
      <el-table-column label="已领取" align="center" prop="neckNum">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleViews(row)">{{
            row.neckNum ?? 0
          }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="剩余" align="center" prop="surplusCount">
        <template #default="{ row }">{{ row.surplusCount ?? 0 }}</template>
      </el-table-column>
      <el-table-column label="已使用" align="center" prop="useNum">
        <template #default="{ row }">{{ row.useNum ?? 0 }}</template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" min-width="200">
        <template #default="{ row }">
          <el-button
            v-hasPermi="['marketing:physicalGoods:failure']"
            link
            type="primary"
            v-if="row.status !== 2"
            @click="handleFailure(row)"
            >失效</el-button
          >
          <el-button
            v-hasPermi="['marketing:physicalGoods:delete']"
            link
            type="primary"
            v-if="row.status === 2"
            @click="handleDelete(row)"
            >删除</el-button
          >
          <el-button
            v-hasPermi="['marketing:physicalGoods:details']"
            link
            type="primary"
            @click="handleDetails(row)"
            >详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList()"
    />

    <dialogDetails ref="dialogRef" @refresh="getList" />
    <receiveList ref="receiveListRef" />
  </div>
</template>
<script setup>
import {
  deleteActivityApi,
  distributeCouponApi,
  getCouponLinkApi,
  getCouponListApi
} from '@/api/marketing/activity/index'
import dialogDetails from './components/details'
import receiveList from './components/receiveList'

import useGlobalStore from '@/store/modules/global'
import { parseTime } from '@/utils/tools'

const globalStore = useGlobalStore()
const route = useRoute()
const router = useRouter()
const showSearch = ref(true)
const loading = ref(false)
const total = ref(0)
const tableList = ref([])
const cityNameOptions = computed(() => globalStore.myCityList)
const queryParams = ref({
  packName: null,
  status: '',
  pageNum: 1,
  pageSize: 10,
  cityName: cityNameOptions.value[0]
})

provide(
  'cityName',
  computed(() => queryParams.value.cityName)
)
const statusOptions = [
  {
    label: '进行中',
    value: 1,
    type: 'success'
  },
  {
    label: '已失效',
    value: 2,
    type: 'info'
  },
  {
    label: '已过期',
    value: 3,
    type: 'info'
  },
  {
    label: '待开始',
    value: 4,
    type: 'warning'
  }
]
const queryRef = ref()

const dialogRef = ref()
const receiveListRef = ref()

function handleSearch(type) {
  if (type) {
    // 搜索
    queryParams.value.pageNum = 1
    getList()
  } else {
    // 重置
    queryParams.value.id = ''
    queryRef.value.resetFields()
    queryParams.value.cityName = globalStore.myCityList.length ? globalStore.myCityList[0] : ''
    console.log('queryParams.cityName', queryParams.value.cityName)
    handleSearch(true)
  }
}

function handleAdd() {
  dialogRef.value.init('', 'add')
}
function handleViews(row) {
  receiveListRef.value.init(row)
  console.log('查看打卡奖励')
}

function handleDelete(row) {
  ElMessageBox.confirm(`确认要删除【${row.couponName}】实物券吗?`, '系统提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    center: false
  }).then(() => {
    deleteActivityApi({ couponId: row.id, status: 0 }).then(() => {
      ElMessage({
        type: 'success',
        message: '操作成功'
      })
      handleSearch(true)
    })
  })
}
function handleFailure(row) {
  console.log('失效了')
  ElMessageBox.confirm('活动将会被强制失效', '操作', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  })
    .then(() => {
      deleteActivityApi({ couponId: row.id, status: 2 }).then(() => {
        ElMessage({
          type: 'success',
          message: '操作成功'
        })
        getList()
      })
    })
    .catch(() => {})
}
function handleDetails(row) {
  dialogRef.value.init(row, 'details')
}
function getList() {
  loading.value = false
  const params = {
    ...queryParams.value,
    type: 6, // 实物券类型
    validStartTime: queryParams.value.time?.length ? queryParams.value.time[0] : '',
    validEndTime: queryParams.value.time?.length ? queryParams.value.time[1] : ''
  }
  delete params.time
  getCouponListApi(params)
    .then((res) => {
      loading.value = false
      tableList.value = res?.data?.rows ?? []
      total.value = res?.data?.total ?? 0
    })
    .catch(() => {
      loading.value = false
      tableList.value = []
      total.value = 0
    })
}

onMounted(() => {
  console.log('实物券', route.query)
  if (route.query.id) {
    queryParams.value.id = route.query.id
    queryParams.value.couponName = route.query.couponName
    queryParams.value.cityName = route.query.cityName
  }
  getList()
})
</script>
<style lang="scss" scoped></style>
